<template>
  <el-row :gutter="20">
    <!-- 左侧考试班级树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <ExamScoreTree @node-click="handleTreeNodeClick" ref="treeRef" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 当前选择显示 -->
      <ContentWrap v-if="currentSelection.type">
        <el-alert
          :title="currentSelectionTitle"
          type="info"
          :closable="false"
          class="mb-15px"
        />
      </ContentWrap>
      
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          :loading="importLoading"
        >
          <Icon icon="ep:upload" class="mr-5px" /> {{ importLoading ? '导入中...' : '导入' }}
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleClearImport"
          v-hasPermi="['system:exam-score:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 清空导入数据
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExportStudentAccounts"
          :loading="exportStudentAccountsLoading"
          v-hasPermi="['system:exam-class-student:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ exportStudentAccountsLoading ? '导出中...' : '导出学生账号' }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleExportTeacherAccounts"
          :loading="exportTeacherAccountsLoading"
          v-hasPermi="['system:exam-class:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ exportTeacherAccountsLoading ? '导出中...' : '导出老师账号' }}
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleExportEquivalentScore"
          :loading="exportEquivalentScoreLoading"
          v-hasPermi="['system:exam-score:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ exportEquivalentScoreLoading ? '导出中...' : '导出等效分' }}
        </el-button>
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          @click="handleDownloadTemplate"-->
<!--        >-->
<!--          <Icon icon="ep:download" class="mr-5px" /> 下载模板-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          @click="handleExport"-->
<!--          :loading="exportLoading"-->
<!--          v-hasPermi="['system:exam-score:export']"-->
<!--        >-->
<!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <!-- 未选择时的提示 -->
        <div v-if="!currentSelection.type" class="text-center py-20">
          <el-empty description="请在左侧选择考试或班级查看对应的学生成绩" />
        </div>
        
        <el-table v-else v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="学生ID" align="center" prop="studentId" />
      <el-table-column label="考号" align="center" prop="studentNo" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="选科组合" align="center" prop="subjectCombination" />
      <el-table-column label="语文" align="center" prop="chineseScore" />
      <el-table-column label="数学" align="center" prop="mathScore" />
      <el-table-column label="英语" align="center" prop="englishScore" />
      <el-table-column label="物理" align="center" prop="physicsScore" />
      <el-table-column label="化学" align="center" prop="chemistryScore" />
      <el-table-column label="生物" align="center" prop="biologyScore" />
      <el-table-column label="政治" align="center" prop="politicsScore" />
      <el-table-column label="历史" align="center" prop="historyScore" />
      <el-table-column label="地理" align="center" prop="geographyScore" />
      <el-table-column label="日语" align="center" prop="japaneseOriginalScore" />
      <el-table-column label="西班牙语" align="center" prop="spanishOriginalScore" />
      <el-table-column label="俄语" align="center" prop="russianOriginalScore" />
      <el-table-column label="总分" align="center" prop="totalScore" />
      <el-table-column label="总分赋分" align="center" prop="totalScoreAssigned" />
      <el-table-column label="组合排名" align="center" prop="combinationRank" />
      <el-table-column label="校内排名" align="center" prop="schoolRank" />
      <el-table-column label="班级排名" align="center" prop="classRank" />
      <el-table-column label="学生所在省份" align="center" prop="province" />
      <el-table-column label="首选科目" align="center" prop="firstSubject" />
      <el-table-column label="次选科目" align="center" prop="secondSubject" />
      <el-table-column label="考试类型" align="center" prop="examType" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
        <!-- 分页 -->
        <Pagination
          v-if="currentSelection.type"
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ExamScoreForm ref="formRef" @success="getList" />
  
  <!-- 特控线设置弹窗 -->
  <ExamControlLineDialog ref="controlLineDialogRef" @success="handleControlLineSuccess" />
  
  <!-- 班级选择弹窗 -->
  <el-dialog
    v-model="showClassSelectDialog"
    title="选择班级"
    width="400px"
    :close-on-click-modal="false"
  >
    <el-form :model="classSelectForm" label-width="80px">
      <el-form-item label="选择班级" required>
        <el-select
          v-model="classSelectForm.classId"
          placeholder="请选择班级"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="classItem in classList"
            :key="classItem.id"
            :label="`${classItem.className}(${classItem.classCode})`"
            :value="classItem.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showClassSelectDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmExportStudentAccounts" :loading="exportStudentAccountsLoading">确定导出</el-button>
    </template>
  </el-dialog>

  <!-- 等效分考试选择弹窗 -->
  <el-dialog
    v-model="showEquivalentScoreDialog"
    title="选择考试导出等效分"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="equivalentScoreForm" label-width="100px">
      <el-form-item label="选择考试" required>
        <el-select
          v-model="equivalentScoreForm.examId"
          placeholder="请选择考试"
          clearable
          style="width: 100%"
          @change="handleExamChange"
        >
          <el-option
            v-for="exam in examList"
            :key="exam.id"
            :label="exam.examName"
            :value="exam.id"
          />
        </el-select>
      </el-form-item>
      
      <!-- 特控线检测结果 -->
      <el-alert
        v-if="equivalentScoreForm.examId && !checkingControlLine"
        :title="controlLineCheckResult.message"
        :type="controlLineCheckResult.hasControlLine ? 'success' : 'warning'"
        :closable="false"
        show-icon
        class="mb-15px"
      />
    </el-form>
    <template #footer>
      <el-button @click="showEquivalentScoreDialog = false">取消</el-button>
      <el-button
        v-if="equivalentScoreForm.examId && !controlLineCheckResult.hasControlLine"
        type="warning"
        @click="goToSetControlLine"
      >
        去设置特控线
      </el-button>
      <el-button 
        type="primary" 
        @click="confirmExportEquivalentScore" 
        :loading="exportEquivalentScoreLoading"
        :disabled="!equivalentScoreForm.examId || !controlLineCheckResult.hasControlLine"
      >
        确定导出
      </el-button>
    </template>
  </el-dialog>

  <!-- 清空导入数据考试选择弹窗 -->
  <el-dialog
    v-model="showClearImportDialog"
    title="选择考试清空导入数据"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="clearImportForm" label-width="100px">
      <el-form-item label="选择考试" required>
        <el-select
          v-model="clearImportForm.examId"
          placeholder="请选择要清空数据的考试"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="exam in examList"
            :key="exam.id"
            :label="exam.examName"
            :value="exam.id"
          />
        </el-select>
      </el-form-item>
      
      <!-- 警告提示 -->
      <el-alert
        title="警告：清空数据后将无法恢复，请谨慎操作！"
        type="warning"
        :closable="false"
        show-icon
        class="mb-15px"
      />
    </el-form>
    <template #footer>
      <el-button @click="showClearImportDialog = false">取消</el-button>
      <el-button 
        type="danger" 
        @click="confirmClearImport" 
        :loading="clearImportLoading"
        :disabled="!clearImportForm.examId"
      >
        确定清空
      </el-button>
    </template>
  </el-dialog>
  
  <!-- 隐藏的文件上传input -->
  <input
    ref="uploadRef"
    type="file"
    accept=".xlsx,.xls"
    style="display: none"
    @change="handleFileUpload"
  />
  
  <!-- 导入进度条弹窗 -->
  <el-dialog
    v-model="showProgressDialog"
    title="导入进度"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="progress-container">
      <el-progress
        :percentage="progressPercentage"
        :status="progressStatus"
        :stroke-width="20"
      />
      <div class="progress-text" style="margin-top: 15px; text-align: center; color: #606266;">
        {{ progressText }}
      </div>
    </div>
  </el-dialog>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ExamScoreApi, ExamScoreVO } from '@/api/system/examscore'
import { ExamClassApi, ExamClassVO } from '@/api/system/examclass'
import { ExamTestApi, ExamTestVO } from '@/api/system/examtest'
import { ExamControlLineApi } from '@/api/system/examcontrolline'
import ExamScoreForm from './ExamScoreForm.vue'
import ExamScoreTree from './ExamScoreTree.vue'
import ExamControlLineDialog from '@/views/system/examtest/ExamControlLineDialog.vue'

/** 学生成绩 列表 */
defineOptions({ name: 'ExamScore' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ExamScoreVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const classList = ref<ExamClassVO[]>([]) // 班级列表数据
const examList = ref<ExamTestVO[]>([]) // 考试列表数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  examId: undefined,
  studentId: undefined,
  studentNo: undefined,
  studentName: undefined,
  examNo: undefined,
  className: undefined,
  classId: undefined,
  subjectCombination: undefined,
  chineseScore: undefined,
  mathScore: undefined,
  englishScore: undefined,
  physicsScore: undefined,
  chemistryScore: undefined,
  biologyScore: undefined,
  politicsScore: undefined,
  historyScore: undefined,
  geographyScore: undefined,
  totalScore: undefined,
  totalScoreAssigned: undefined,
  combinationRank: undefined,
  schoolRank: undefined,
  classRank: undefined,
  gradeRank: undefined,
  province: undefined,
  firstSubject: undefined,
  secondSubject: undefined,
  examType: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const importLoading = ref(false) // 导入的加载中
const exportStudentAccountsLoading = ref(false) // 导出学生账号的加载中
const exportTeacherAccountsLoading = ref(false) // 导出老师账号的加载中
const exportEquivalentScoreLoading = ref(false) // 导出等效分的加载中
const checkingControlLine = ref(false) // 检测特控线的加载中
const uploadRef = ref() // 上传组件引用
const showClassSelectDialog = ref(false) // 班级选择弹窗显示状态
const classSelectForm = reactive({
  classId: undefined
}) // 班级选择表单数据
const treeRef = ref() // 树形菜单组件引用

// 等效分导出相关
const showEquivalentScoreDialog = ref(false) // 等效分考试选择弹窗显示状态
const equivalentScoreForm = reactive({
  examId: undefined
}) // 等效分考试选择表单数据
const controlLineCheckResult = reactive({
  hasControlLine: false,
  message: ''
}) // 特控线检测结果
const controlLineDialogRef = ref() // 特控线设置对话框引用

// 清空导入数据相关
const showClearImportDialog = ref(false) // 清空导入数据弹窗显示状态
const clearImportForm = reactive({
  examId: undefined
}) // 清空导入数据表单数据
const clearImportLoading = ref(false) // 清空导入数据加载状态

// 当前选择的考试或班级
const currentSelection = reactive({
  type: '', // 'exam' 或 'class'
  examId: undefined,
  classId: undefined,
  label: ''
})

// 当前选择的标题
const currentSelectionTitle = computed(() => {
  if (!currentSelection.type) return ''
  if (currentSelection.type === 'exam') {
    return `当前查看：${currentSelection.label} - 所有班级成绩`
  } else if (currentSelection.type === 'class') {
    return `当前查看：${currentSelection.label} - 班级成绩`
  }
  return ''
})

// 进度条相关
const showProgressDialog = ref(false) // 是否显示进度条弹窗
const progressPercentage = ref(0) // 进度百分比
const progressStatus = ref<'success' | 'exception' | 'warning' | ''>('') // 进度状态
const progressText = ref('') // 进度文字
let progressTimer: NodeJS.Timeout | null = null // 进度条定时器

/** 处理树形菜单节点点击 */
const handleTreeNodeClick = (nodeData: any) => {
  // 更新当前选择
  currentSelection.type = nodeData.type
  currentSelection.examId = nodeData.examId
  currentSelection.classId = nodeData.classId
  currentSelection.label = nodeData.label
  
  // 更新查询参数
  if (nodeData.type === 'exam') {
    // 选择考试：显示该考试所有班级的成绩
    queryParams.examId = nodeData.examId
    queryParams.classId = undefined
  } else if (nodeData.type === 'class') {
    // 选择班级：显示该考试该班级的成绩
    queryParams.examId = nodeData.examId
    queryParams.classId = nodeData.classId
  }
  
  // 重置分页并查询
  queryParams.pageNo = 1
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ExamScoreApi.getExamScorePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取班级列表 */
const getClassList = async () => {
  try {
    const data = await ExamClassApi.getAllExamClasses()
    classList.value = data || []
  } catch (error) {
    console.error('获取班级列表失败:', error)
  }
}

/** 获取考试列表 */
const getExamList = async () => {
  try {
    const data = await ExamTestApi.getSimpleExamTestList()
    examList.value = data.list || []
  } catch (error) {
    console.error('获取考试列表失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 清除树形菜单选择
  currentSelection.type = ''
  currentSelection.examId = undefined
  currentSelection.classId = undefined
  currentSelection.label = ''
  queryParams.examId = undefined
  queryParams.classId = undefined
  handleQuery()
}

/** 修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ExamScoreApi.deleteExamScore(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ExamScoreApi.exportExamScore(queryParams)
    download.excel(data, '学生成绩.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导出学生账号按钮操作 */
const handleExportStudentAccounts = async () => {
  // 重置表单
  classSelectForm.classId = undefined
  // 重新获取班级列表确保数据最新
  await getClassList()
  // 显示弹窗
  showClassSelectDialog.value = true
}

/** 确认导出学生账号 */
const confirmExportStudentAccounts = async () => {
  try {
    // 检查是否选择了班级
    if (!classSelectForm.classId) {
      message.error('请选择班级')
      return
    }
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportStudentAccountsLoading.value = true
    const data = await ExamScoreApi.exportStudentAccounts({ classId: classSelectForm.classId })
    download.excel(data, '学生账号信息.xls')
    message.success('学生账号导出成功')
    // 关闭弹窗
    showClassSelectDialog.value = false
  } catch {
  } finally {
    exportStudentAccountsLoading.value = false
  }
}

/** 导出老师账号按钮操作 */
const handleExportTeacherAccounts = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportTeacherAccountsLoading.value = true
    // 支持分页查询参数（年级、班级名称等筛选条件）
    const exportParams = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      className: queryParams.className,
      classId: queryParams.classId
    }
    const data = await ExamScoreApi.exportTeacherAccounts(exportParams)
    download.excel(data, '班主任账号信息.xls')
    message.success('班主任账号导出成功')
  } catch {
  } finally {
    exportTeacherAccountsLoading.value = false
  }
}

/** 导出等效分按钮操作 */
const handleExportEquivalentScore = async () => {
  // 重置表单
  equivalentScoreForm.examId = undefined
  controlLineCheckResult.hasControlLine = false
  controlLineCheckResult.message = ''
  // 重新获取考试列表确保数据最新
  await getExamList()
  // 显示弹窗
  showEquivalentScoreDialog.value = true
}

/** 考试改变时检测特控线 */
const handleExamChange = async (examId: number) => {
  if (!examId) {
    controlLineCheckResult.hasControlLine = false
    controlLineCheckResult.message = ''
    return
  }
  
  checkingControlLine.value = true
  try {
    // 查询该考试的特控线配置
    const data = await ExamControlLineApi.getExamControlLinePage({
      examId: examId,
      pageNo: 1,
      pageSize: 10
    })
    
    if (data.list && data.list.length > 0) {
      controlLineCheckResult.hasControlLine = true
      controlLineCheckResult.message = '该考试已设置特控线，可以导出等效分'
    } else {
      controlLineCheckResult.hasControlLine = false
      controlLineCheckResult.message = '该考试还未设置特控线，请先设置特控线后再导出等效分'
    }
  } catch (error) {
    console.error('检测特控线失败:', error)
    controlLineCheckResult.hasControlLine = false
    controlLineCheckResult.message = '检测特控线失败，请重试'
  } finally {
    checkingControlLine.value = false
  }
}

/** 打开特控线设置对话框 */
const goToSetControlLine = () => {
  if (!equivalentScoreForm.examId) {
    message.error('请先选择考试')
    return
  }
  // 打开特控线设置对话框
  controlLineDialogRef.value.open(equivalentScoreForm.examId)
}

/** 特控线设置成功回调 */
const handleControlLineSuccess = async () => {
  message.success('特控线设置成功')
  // 重新检测特控线
  if (equivalentScoreForm.examId) {
    await handleExamChange(equivalentScoreForm.examId)
  }
}

/** 确认导出等效分 */
const confirmExportEquivalentScore = async () => {
  try {
    // 检查是否选择了考试
    if (!equivalentScoreForm.examId) {
      message.error('请选择考试')
      return
    }
    
    // 检查是否已设置特控线
    if (!controlLineCheckResult.hasControlLine) {
      message.error('该考试还未设置特控线，请先设置特控线')
      return
    }
    
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportEquivalentScoreLoading.value = true
    const data = await ExamScoreApi.exportEquivalentScore({ examId: equivalentScoreForm.examId })
    download.excel(data, '等效分.xls')
    message.success('等效分导出成功')
    // 关闭弹窗
    showEquivalentScoreDialog.value = false
  } catch {
  } finally {
    exportEquivalentScoreLoading.value = false
  }
}

/** 清空导入数据按钮操作 */
const handleClearImport = async () => {
  // 重置表单
  clearImportForm.examId = undefined
  // 重新获取考试列表确保数据最新
  await getExamList()
  // 显示弹窗
  showClearImportDialog.value = true
}

/** 确认清空导入数据 */
const confirmClearImport = async () => {
  try {
    // 检查是否选择了考试
    if (!clearImportForm.examId) {
      message.error('请选择考试')
      return
    }
    
    // 获取选中的考试名称
    const selectedExam = examList.value.find(exam => exam.id === clearImportForm.examId)
    const examName = selectedExam?.examName || '该考试'
    
    // 二次确认
    await message.confirm(
      `确定要清空"${examName}"的所有成绩数据吗？清空后将无法恢复！`,
      '警告'
    )
    
    // 发起清空请求
    clearImportLoading.value = true
    const result = await ExamScoreApi.clearImportedScores(clearImportForm.examId)
    
    // 显示成功消息
    message.success(`成功清空 ${result} 条成绩数据`)
    
    // 关闭弹窗
    showClearImportDialog.value = false
    
    // 刷新列表
    await getList()
    
    // 刷新树形菜单
    if (treeRef.value) {
      await treeRef.value.loadTree()
    }
  } catch (error: any) {
    // 如果用户取消了操作，不显示错误
    if (error !== 'cancel') {
      console.error('清空导入数据失败:', error)
    }
  } finally {
    clearImportLoading.value = false
  }
}

/** 开始进度条 */
const startProgress = (fileSizeMB: number) => {
  showProgressDialog.value = true
  progressPercentage.value = 0
  progressStatus.value = ''
  
  // 根据文件大小设置不同的进度文字和速度
  if (fileSizeMB > 10) {
    progressText.value = '正在处理大文件，请耐心等待...'
  } else {
    progressText.value = '正在导入数据，请稍候...'
  }
  
  // 模拟进度增长
  const increment = fileSizeMB > 10 ? 0.5 : 1 // 大文件进度更慢
  const interval = fileSizeMB > 10 ? 800 : 500 // 大文件更新间隔更长
  
  progressTimer = setInterval(() => {
    if (progressPercentage.value < 85) {
      progressPercentage.value = Math.round((progressPercentage.value + increment) * 100) / 100
    } else if (progressPercentage.value < 95) {
      progressPercentage.value = Math.round((progressPercentage.value + 0.2) * 100) / 100 // 接近完成时更慢
    }
  }, interval)
}

/** 完成进度条 */
const completeProgress = (success: boolean = true) => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
  
  progressPercentage.value = 100
  progressStatus.value = success ? 'success' : 'exception'
  progressText.value = success ? '导入完成！' : '导入失败！'
  
  // 2秒后关闭弹窗
  setTimeout(() => {
    showProgressDialog.value = false
    progressPercentage.value = 0
    progressStatus.value = ''
    progressText.value = ''
  }, 2000)
}

/** 导入按钮操作 */
const handleImport = () => {
  uploadRef.value?.click()
}

/** 文件上传处理 */
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) {
    return
  }

  // 验证文件类型
  const allowedTypes = ['.xlsx', '.xls']
  const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
  if (!allowedTypes.includes(fileExtension)) {
    message.error('请选择Excel文件（.xlsx或.xls格式）')
    target.value = ''
    return
  }

  // 验证文件大小（限制为50MB）
  const maxSize = 50 * 1024 * 1024
  if (file.size > maxSize) {
    message.error('文件大小不能超过50MB')
    target.value = ''
    return
  }

  try {
    importLoading.value = true
    
    // 计算文件大小并开始进度条
    const fileSizeMB = file.size / (1024 * 1024)
    startProgress(fileSizeMB)
    
    const formData = new FormData()
    formData.append('file', file)
    
    // 为导入请求设置更长的超时时间（5分钟）
    const result = await ExamScoreApi.importExamScoreWithTimeout(formData, 300000)
    
    // 导入成功，完成进度条
    completeProgress(true)
    
    // 根据返回结果显示不同的消息
    setTimeout(() => {
      if (result && result.successCount !== undefined) {
        if (result.failureCount > 0) {
          message.warning(`导入完成！成功导入 ${result.successCount} 条记录，失败 ${result.failureCount} 条记录`)
        } else {
          message.success(`导入成功！共导入 ${result.successCount} 条记录`)
        }
      } else {
        message.success('导入成功！')
      }
    }, 1000) // 延迟显示结果消息，让用户看到进度条完成
    
    // 刷新列表
    setTimeout(async () => {
      await getList()
    }, 2500) // 在进度条弹窗关闭后刷新列表
    
  } catch (error: any) {
    console.error('导入失败:', error)
    
    // 导入失败，完成进度条并显示失败状态
    completeProgress(false)
    
    let errorMsg = '导入失败，请检查文件格式和内容'
    
    // 处理超时错误
    if (error?.code === 'ECONNABORTED' || error?.message?.includes('timeout')) {
      errorMsg = '导入超时，请检查网络连接或尝试分批导入较小的文件'
    } else if (error?.response?.data?.msg) {
      errorMsg = error.response.data.msg
    } else if (error?.message) {
      errorMsg = error.message
    }
    
    // 延迟显示错误消息
    setTimeout(() => {
      message.error(errorMsg)
    }, 1000)
    
  } finally {
    importLoading.value = false
    // 清空文件选择
    target.value = ''
  }
}

/** 下载导入模板 */
const handleDownloadTemplate = async () => {
  try {
    const data = await ExamScoreApi.importTemplate()
    download.excel(data, '学生成绩导入模板.xlsx')
  } catch (error) {
    message.error('下载模板失败')
  }
}

/** 初始化 **/
onMounted(async () => {
  // 获取班级列表和考试列表
  await getClassList()
  await getExamList()
  
  // 如果有默认的查询参数（如从其他页面跳转过来），则加载数据
  if (queryParams.examId || queryParams.classId) {
    await getList()
  }
  // 树形组件会自动加载数据并选择第一个节点，无需手动触发
})

/** 组件销毁时清理定时器 **/
onUnmounted(() => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
})
</script>
